package com.zhkc.iess.online.test01.service;

import com.zhkc.iess.online.test01.constant.CommonConstant;
import com.zhkc.iess.online.test01.core.HJ212Data;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 管理与现场机的会话
 */
@Service
public class ChannelRemotingService {


    @Autowired
    private DeviceRecriminateService deviceRecriminateService;
    public void registerMN(Channel channel) {
        //将设备MN号 和 channel 关联
        CommonConstant.clients.computeIfAbsent(channel.attr(HJ212Data.MN_ATTR).get(), mn -> {
            //设置现场机时间
            HJ212Data hj212Data = deviceRecriminateService.build1012(channel);
            channel.writeAndFlush(hj212Data);
            return channel;
        });
    }

    public void addConnectionEntry(Channel channel) {
        //添加、移除，同一个设备的断连并发（几乎不存在），暂不考虑并发问题
        CommonConstant.connections.put(channel.id(), channel);
    }

    public Channel removeConnection(final Object channelId) {
        Channel remove = CommonConstant.connections.remove(channelId);
        Optional.ofNullable(remove.attr(HJ212Data.MN_ATTR).get())
                .ifPresent(mn -> CommonConstant.clients.remove(mn));
        return remove;
    }

    public void handleComplete(HJ212Data msg) {
        //todo 处理返回的应答，例如修改现场机时间，，下位机返回执行结果，更新数据库执行结果字段。

    }


}
